package com.liesheng.haylou.net;

import android.util.Log;


import com.liesheng.haylou.utils.AppUtils;
import com.liesheng.haylou.utils.sp.SpUtil;

import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Date:2019/11/6
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 * 网络请求拦截器
 * 可以做以下处理:1.打印日志  2.添加公共入参  3.token 过期处理
 */
public class MyInterceptor implements Interceptor {

    private final String TAG = "MyInterceptor";

    /**
     * 请求访问quest
     * response拦截器
     */
    public Interceptor logInterceptor = chain -> {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(chain.request());

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Log.e(TAG, "----------Request Start----------------");
        Log.e(TAG, "| " + request.toString() + request.headers().toString());
        Log.e(TAG, "| Response:" + AppUtils.unicodeToUTF_8(content));
        Log.e(TAG, "----------Request End:" + duration + "毫秒----------");
        return response.newBuilder()
                .body(ResponseBody.create(mediaType, content))
                .build();
    };

    public Interceptor headInterceptor = chain -> {

        Request request = chain.request().newBuilder()
                .addHeader("Content-type", "application/json")
                .addHeader("deviceType", "2")
                .addHeader("token",SpUtil.getToken())
                .build();

        Log.e(TAG, "----------Request " + request.headers() + "----------");
        return chain.proceed(request);
    };

    @Override
    public Response intercept(Chain chain) throws IOException {
        return null;
    }
}
